package com.mall.order.rocketmq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @author xudengfeng
 * @date 2020/12/23 21:26
 */
@Slf4j
@Component //注册到容器
public class MqProducer {

    private DefaultMQProducer mqProducer;

    @PostConstruct
    public void init() {
        mqProducer = new DefaultMQProducer("producer_first");
        mqProducer.setNamesrvAddr("localhost:9876");
        try {
            mqProducer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public Boolean sendOrderDelayMsg(String orderId) {
        Message message = new Message();
        message.setTopic("order_topic");
        message.setBody("orderDelay".getBytes(Charset.forName("utf-8")));
        log.info("延时消息已生成......");
        message.setDelayTimeLevel(6);
        try {
            SendResult sendResult = mqProducer.send(message);
            SendStatus sendStatus = sendResult.getSendStatus();
            if (SendStatus.SEND_OK.equals(sendStatus)) {
                log.info("订单延时消息已发送...");
                return true;
            }
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

}
